package com.jjb.spider.mqtt.ctx;

import com.jjb.spider.mqtt.model.TopSubscribeMessage;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class MqttChannelHandlerContext {

    private ChannelHandlerContext context;

    private String deviceId;

    private Boolean isLogin;

    /**
     * 当前连接监听的主题
     */
    private Set<TopSubscribeMessage> topics = new HashSet<>();

    public MqttChannelHandlerContext(ChannelHandlerContext context) {
        this.context = context;
        this.isLogin = false;
    }

    public ChannelHandlerContext getContext() {
        return context;
    }

    public void setContext(ChannelHandlerContext context) {
        this.context = context;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }


    public void setLogin(Boolean login) {
        isLogin = login;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public ChannelFuture writeAndFlush(Object message) {
        return this.context.writeAndFlush(message);
    }

    public String getChannelId() {
        return context.channel().id().asLongText();
    }

    public void saveSubscribe(List<TopSubscribeMessage> topics) {
        if(topics != null) {
            this.topics.addAll(topics);
        }
    }

    public void unsubscribe(Collection<String> topics) {
        if( this.topics != null ) {

            List<TopSubscribeMessage> delTop = this.topics.stream().filter(topSubscribeMessage -> topics.contains(topSubscribeMessage.getTopic()))
                    .collect(Collectors.toList());
            if(delTop != null) {
                this.topics.removeAll(delTop);
            }
        }
    }

    public boolean isSupportTop(String topics) {
        if( this.topics == null || this.topics.isEmpty() ) {
            return false;
        } else {
            boolean result = false;
            for( TopSubscribeMessage topic : this.topics ) {
                if ( checkTopic(topic.getTopic(), topics) ) {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }

    public List<TopSubscribeMessage> getSubscribeTopics(String topic) {
        return topics.stream().filter(t -> checkTopic(t.getTopic(), topic)).collect(Collectors.toList());
    }

    private boolean checkTopic(String topic, String topics) {
        return topics.equals(topic);
    }
}
